import { Button, Card, Form, message, Table } from "antd"
import usePagination from "../../../hooks/usePagination"
import { gql, useLazyQuery, useMutation } from "@apollo/client"
import { BaseFields, PaginationFields } from "../../../queries/base"
import { useColumns, useDataSource } from "../../../hooks/useTable"
import { UserPowerFields } from "../../../queries/user"
import dayjs from "dayjs"
import DelPopover from "../../../components/DelPopover"
import gqlError from "../../../libs/gql-error"
import SearchForm from "../../../components/SearchForm"
import { FormFactoryItem } from "../../../components/FormFactory"
import SearchButtonGroup from "../../../components/SearchButtonGroup"
import { FindUsersQuery, FindUsersResult } from "../system/users/page"
import { useMemo } from "react"
import FormModal from "../../../components/FormModal"
import useOpen from "../../../hooks/useOpen"


const QueryUserPowerPagination = gql`
  query QueryUserPowerPagination(
    $page: Int,
    $size: Int,
    $userId: Int,
    $chapterId: Int,
  ){
    queryUserPowerPagination(
      page: $page,
      size: $size,
      userId: $userId,
      chapterId: $chapterId,
    ){
      ${PaginationFields}
      data{
        ${BaseFields}
        ${UserPowerFields}
        sys_user{
          id
          name
        }
        sys_test_chapter{
          id
          name
          test{
            name
          }
        }
      }
    }
  }
`
const DeletePowerMutation = gql`
  mutation DeletePower(
    $id: Int!,
  ){
    removePower(
      id: $id,
    ){
      id
    }
  }
`
export const QueryTestChaptersByNameQuery = gql`
  query QueryTestChaptersByName(
    $name: String,
  ){
    queryTestChaptersByName(
      name: $name,
    ){
      id
      name
      test{
        name
      }
    }
  }
`
export interface QueryTestChaptersByNameResult {
  queryTestChaptersByName: {
    id: number
    name: string
    test: {
      name: string
    }
  }[]
}
const AddPowerMutation = gql`
  mutation AddPower(
    $userId: Int!,
    $chapterId: Int!,
    $end_time: String!,
  ){
    addPower(
      sys_userId: $userId,
      sys_test_chapterId: $chapterId,
      end_time: $end_time,
    ){
      id
    }
  }
`
const AdminOrderPage = () => {
  const {
    pagination,
    refetch,
    research,
    data
  } = usePagination({
    query: QueryUserPowerPagination,
    name: "queryUserPowerPagination"
  })
  const [del] = useMutation(DeletePowerMutation, {
    onCompleted: () => {
      message.success("删除成功")
      refetch()
    },
    onError: (err) => {
      gqlError(err)
    }
  })
  const dataSource = useDataSource(data)
  const columns = useColumns([{
    title: "用户",
    dataIndex: ["sys_user", "name"],
    type: "text"
  }, {
    title: "试卷等级",
    dataIndex: ["sys_test_chapter", "name"],
    type: "text"
  }, {
    title: "试卷分类",
    dataIndex: ["sys_test_chapter", "test", "name"],
    type: "text"
  }, {
    title: "到期时间",
    render: (record: any) => {
      return (
        <div>
          {dayjs(record.end_time).format("YYYY-MM-DD")}
        </div>
      )
    }
  }, {
    title: "操作",
    render: (record: any) => {
      return (
        <div>
          <DelPopover
            onDelete={() => {
              del({
                variables: {
                  id: record.id
                }
              })
            }}
          >
            <Button danger>删除</Button>
          </DelPopover>
        </div>
      )
    }
  }])
  const [findUsers, usersResult] = useLazyQuery<FindUsersResult>(FindUsersQuery)
  const users = useMemo(() => usersResult.data?.findUsers.data || [], [usersResult.data?.findUsers.data])
  const [findChapters, chaptersResult] = useLazyQuery<QueryTestChaptersByNameResult>(QueryTestChaptersByNameQuery)
  const chapters = useMemo(() => chaptersResult.data?.queryTestChaptersByName || [], [chaptersResult.data?.queryTestChaptersByName])

  const searchOptions: FormFactoryItem[] = [{
    type: "select",
    label: "搜索用户",
    name: "userId",
    onSearch: (value: string) => {
      findUsers({
        variables: {
          name: value,
          page: 1,
          size: 20
        }
      })
    },
    options: users.map((item) => ({
      label: item.name,
      value: item.id
    })),
    filterOption: false,
    showSearch: true
  }, {
    type: "select",
    label: "搜索试卷",
    name: "chapterId",
    options: chapters.map((item) => ({
      label: `${item.test?.name}${item.name}`,
      value: item.id
    })),
    onSearch: (name: string) => {
      findChapters({
        variables: {
          name
        }
      })
    },
    filterOption: false,
    showSearch: true,
    style: {
      minWidth: 300
    }
  }]
  const [form] = Form.useForm()
  const [open, onOpen, onCancel] = useOpen()
  const [createForm] = Form.useForm()
  return (
    <Card>
      <div
        className="flex gap-2"
      >
        <SearchForm
          options={searchOptions}
          name="order"
          formProps={{
            layout: "inline",
            onFinish: (variables) => research({ variables }),
            form
          }}
        />
      </div>
      <div className="flex gap-2 my-2">
        <FormModal
          title="新增"
          query={AddPowerMutation}
          open={open}
          onCancel={onCancel}
          options={[{
            type: "select",
            label: "搜索用户",
            name: "userId",
            onSearch: (value: string) => {
              findUsers({
                variables: {
                  name: value,
                  page: 1,
                  size: 20
                }
              })
            },
            options: users.map((item) => ({
              label: item.name,
              value: item.id
            })),
            filterOption: false,
            showSearch: true
          }, {
            type: "select",
            label: "搜索试卷",
            name: "chapterId",
            options: chapters.map((item) => ({
              label: `${item.test?.name}${item.name}`,
              value: item.id
            })),
            onSearch: (name: string) => {
              findChapters({
                variables: {
                  name
                }
              })
            },
            filterOption: false,
            showSearch: true,
            style: {
              minWidth: 300
            }
          }, {
            type: "date",
            label: "到期时间",
            name: "end_time",
            required: true
          }]}
          onCompleted={() => {
            message.success("新增成功")
            refetch()
            onCancel()
          }}
          onError={gqlError}
          form={createForm}
        />
        <Button
          type="primary"
          onClick={onOpen}
        >
          新增
        </Button>
        <SearchButtonGroup
          onSearch={form.submit}
          onReset={form.resetFields}
        />
      </div>
      <Table
        pagination={false}
        dataSource={dataSource}
        columns={columns}
      />
      <div className="flex justify-end mt-3">
        {pagination}
      </div>
    </Card>
  )
}
export default AdminOrderPage